package com.guigu.dealservice.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.guigu.common.utils.R;
import com.guigu.dealservice.entity.SalesData;
import com.guigu.dealservice.entity.Total;
import com.guigu.dealservice.mapper.TotalMapper;
import com.guigu.dealservice.service.TotalService;
import com.guigu.dealservice.vo.TotalVo;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class TotalServiceImpl extends ServiceImpl<TotalMapper, Total> implements TotalService {
    @Autowired
    private TotalMapper totalMapper;
    @Override
    public R queryTotalList(TotalVo vo, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Total> queryTotalList = totalMapper.queryTotalList(vo);
        PageInfo<Total> pageInfo = new PageInfo<>(queryTotalList);
        return R.ok().data("pageInfo", pageInfo);
    }

    /**
     * 获取用于图表展示的销售数据
     * @param months 查询的月份数
     * @return 处理后的图表数据
     */
    @Override
    public R querySalesByMonthAndSalesman(Integer months) {
        List<SalesData> rawData = totalMapper.querySalesByMonthAndSalesman(months);

        // 获取所有月份（排序）
        List<String> monthsList = rawData.stream()
                .map(SalesData::getMonthLabel)
                .distinct()
                .collect(Collectors.toList());

        // 获取所有业务员
        List<String> salesmen = rawData.stream()
                .map(SalesData::getSalesmanName)
                .distinct()
                .collect(Collectors.toList());

        // 为每个业务员构建数据序列
        Map<String, List<Double>> seriesData = salesmen.stream()
                .collect(Collectors.toMap(
                        salesman -> salesman,
                        salesman -> {
                            List<Double> data = new ArrayList<>();
                            for (String monthLabel : monthsList) {
                                Double amount = rawData.stream()
                                        .filter(d -> d.getMonthLabel().equals(monthLabel)
                                                && d.getSalesmanName().equals(salesman))
                                        .map(d -> d.getSalesAmount() != null ? d.getSalesAmount().doubleValue() : 0.0)
                                        .findFirst()
                                        .orElse(0.0);
                                data.add(amount);
                            }
                            return data;
                        }
                ));

        // 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("months", monthsList);
        result.put("salesmen", salesmen);
        result.put("seriesData", seriesData);

        return R.ok().data("chartData", result);
    }

    @Override
    public R querySalesByMonthAndSalesman2(Integer eid, Integer months) {
        // 直接查询指定eid的月度销售数据（无需关联业务员分组）
        List<SalesData> rawData = totalMapper.querySalesByMonthAndSalesman2(eid, months);

        // 提取所有月份并去重排序（按时间自然排序）
        List<String> monthsList = rawData.stream()
                .map(SalesData::getMonthLabel)
                .distinct()
                .sorted() // 按月份排序（如2025-01, 2025-02）
                .collect(Collectors.toList());

        // 构建月度销售金额数据（按月份顺序排列）
        List<Double> salesAmounts = new ArrayList<>();
        for (String monthLabel : monthsList) {
            // 查找当前月份的销售金额，无数据则补0
            Double amount = rawData.stream()
                    .filter(d -> d.getMonthLabel().equals(monthLabel))
                    .map(d -> d.getSalesAmount() != null ? d.getSalesAmount().doubleValue() : 0.0)
                    .findFirst()
                    .orElse(0.0);
            salesAmounts.add(amount);
        }

        // 构建返回结果（只包含月份和对应eid的销售数据）
        Map<String, Object> result = new HashMap<>();
        result.put("months", monthsList);       // 月份列表
        result.put("salesAmounts", salesAmounts); // 对应月份的销售金额

        return R.ok().data("chartData", result);
    }
}
